package com.zt.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zt.api.UserInfoFeign;
import com.zt.service.TransactionRecordService;
import com.zt.system.CardTable;
import com.zt.service.CardTableService;
import com.zt.mapper.CardTableMapper;
import com.zt.system.TransactionRecord;
import com.zt.system.vo.CardTableVO;
import com.zt.user.UserInfo;
import com.zt.utils.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.Date;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

/**
 * @author 不.凌
 * @description 针对表【card_table】的数据库操作Service实现
 * @createDate 2024-09-03 17:46:33
 */
@Service
public class CardTableServiceImpl extends ServiceImpl<CardTableMapper, CardTable>
        implements CardTableService {

    @Resource
    private UserInfoFeign userInfoFeign;
    @Resource
    private TransactionRecordService transactionRecordService;
    @Resource
    private CardTableMapper cardTableMapper;

    //    添加信用卡
    @Override
    public Result cardTableSave(UserInfo userInfo) {
        if (userInfo == null) {
            return Result.error("信息不能为空");
        }

        UserInfo userInfoByUserInfo = userInfoFeign.getUserInfoByUserInfo(userInfo.getIdCard());

        if (userInfoByUserInfo == null) {
            return Result.error("您填写的信息有误(请检查您的姓名和身份证是否一致）");
        }
        if (!(userInfoByUserInfo.getIdCard().equals(userInfo.getIdCard())
                && userInfoByUserInfo.getName().equals(userInfo.getName())
                && userInfoByUserInfo.getUsername().equals(userInfo.getUsername()))) {
            return Result.error("您填写的信息有误(请检查您的姓名和身份证是否一致）");
        }
//        判断该用户信用卡是否超过五张，如果超过提示，如果不超过进行申请
        UserInfo userInfoUserId1 = userInfoFeign.getUserInfoUserId();
        List<CardTable> list = this.list(Wrappers.<CardTable>lambdaQuery()
                .eq(userInfoUserId1.getUserId() != null, CardTable::getUserId, userInfoUserId1.getUserId())
                .in(CardTable::getStatus,1,2 ));
        if (list.size()>=5){
            return Result.error("您最多只能办理五张信用卡，无法在申请");
        }

        boolean save = false;
        CardTable cardTable = new CardTable();
//            随机生成6开头的19位数信用卡号
        Random random = new Random();
        StringBuilder cardNumber = new StringBuilder("6");
        for (int i = 1; i < 19; i++) {
            cardNumber.append(random.nextInt(10));
        }
        cardTable.setCardNumber(String.valueOf(cardNumber));

        //根据用户的信用分设置用户的信用额度是多少
        //70-100时额度为5000    50-70时额度为2000   50以下时额度为0
        if (userInfoByUserInfo.getCreditScore() >= 50 && userInfoByUserInfo.getCreditScore() <= 100) {
            cardTable.setCreditLimit(BigDecimal.valueOf(5000.00));
        }
//        else if (userInfoByUserInfo.getCreditScore() < 70 && userInfoByUserInfo.getCreditScore() > 50) {
//            cardTable.setCreditLimit(BigDecimal.valueOf(2000.00));
//        }
        else if (userInfoByUserInfo.getCreditScore() <= 49) {
            return Result.error("您的信用分低于50不能申请信用卡");
        }
//            通过userInfoFeign接口调用UserInfoUserId获取id
        UserInfo userInfoUserId = userInfoFeign.getUserInfoUserId();
        cardTable.setUserId(userInfoUserId.getUserId());

//            测试假如当前用户ID为1
//                cardTable.setUserId(1);
        save = this.save(cardTable);

        return save ? Result.success("添加成功") : Result.error("添加失败");
    }

    //    查询当前用户信用卡的进度
    @Override
    public Result cardTableProgressQueryByUserId() {
        UserInfo userInfoUserId = userInfoFeign.getUserInfoUserId();
        List<CardTable> list = this.list(Wrappers.<CardTable>lambdaQuery()
                .eq(userInfoUserId.getUserId() != null, CardTable::getUserId, userInfoUserId.getUserId()));
        return Result.success(list);
    }

    //查询所有已经通过审核的信用卡信息
    @Override
    public Result cardTableByStatus() {
        UserInfo userInfoUserId = userInfoFeign.getUserInfoUserId();
        List<CardTable> list = this.list(Wrappers.<CardTable>lambdaQuery()
                .in(CardTable::getStatus, 1, 2)
                .eq(userInfoUserId.getUserId()!=null,CardTable::getUserId,userInfoUserId.getUserId()));
        return Result.success(list);
    }

    //    根据当前用户信用分来判断信用卡额度是多少
    @Override
    public Result cardTableByCreditScore() {
        // 月末
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        Date endOfMonthDate = calendar.getTime();


        UserInfo userInfoUserId = userInfoFeign.getUserInfoUserId();
        List<CardTable> list = this.list(Wrappers.<CardTable>lambdaQuery()
                .eq(userInfoUserId.getUserId() != null, CardTable::getUserId, userInfoUserId.getUserId()));


        Boolean update = false;


        for (CardTable cardTable : list) {
            List<TransactionRecord> transactionRecords = transactionRecordService.transactionRecordByCardId(cardTable.getCardId());
//            算出所有的使用的额度
            BigDecimal reduce = transactionRecords.stream().map(TransactionRecord::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            System.out.println("算出所有的使用的额度"+reduce);


            List<TransactionRecord> transactionPayBackRecords = transactionRecordService.transactionPayBackRecordByCardId(cardTable.getCardId());
//            算出所有的重置的额度
            BigDecimal reducePayBack = transactionPayBackRecords.stream().map(TransactionRecord::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            System.out.println("算出所有的还款的额度"+reducePayBack);



            if (userInfoUserId.getCreditScore() >= 50 && userInfoUserId.getCreditScore() <= 100) {
                BigDecimal bigDecimal = new BigDecimal(5000);
                if (cardTable.getStatus() != 0) {
                    cardTable.setStatus(1);
                    cardTable.setDeadline(endOfMonthDate);
                    BigDecimal subtract = bigDecimal.subtract(reduce);
                    System.out.println("取现使用的额度"+subtract);
                    BigDecimal add = subtract.add(reducePayBack);
                    System.out.println("还款使用的额度"+add);
                    cardTable.setRemaining(add);
                    BigDecimal subtract1 = cardTable.getCreditLimit().subtract(add);
                    cardTable.setBalance(subtract1);
                }
                cardTable.setCreditLimit(bigDecimal);
                System.err.println("要修改的数据"+cardTable);
                this.updateById(cardTable);
                update = true;
            }
//            else if (userInfoUserId.getCreditScore() <= 69 && userInfoUserId.getCreditScore() >= 50) {
//                BigDecimal bigDecimal = new BigDecimal(2000);
//                if (cardTable.getStatus() != 0) {
//                    cardTable.setStatus(1);
//                    cardTable.setDeadline(endOfMonthDate);
//                    cardTable.setBalance(reduce);
//                }
//                cardTable.setCreditLimit(bigDecimal);
//                this.updateById(cardTable);
//                update = true;
//            }
            else if (userInfoUserId.getCreditScore() <= 49) {
                    if (cardTable.getStatus() != 0) {
                        cardTable.setStatus(2);
                    }
                    BigDecimal bigDecimal = new BigDecimal(0);
                    cardTable.setCreditLimit(bigDecimal);
                    this.updateById(cardTable);
                    update = true;
            }
        }
        return update ? Result.success("操作成功") : Result.error("操作失败");
    }
    //    根据信用卡号id进行查询单个数据拿到信息
    @Override
    public Result cardTableByCardId(Integer cardId) {
        System.err.println(cardId);
        if (cardId!=null) {
            CardTable one = this.getOne(Wrappers.<CardTable>lambdaQuery()
                    .eq( CardTable::getCardId, cardId));
            return Result.success(one);
        }
        return null;
    }

    @Override
    public Result cardTableVOTiXian(CardTableVO cardTableVO) {

        return null;
    }

    @Override
    public Result cardTableUpdateStatusByCardId(Integer cardId) {
        int i = cardTableMapper.cardTableUpdateStatusByCardId(cardId);
        this.cardTableByCreditScore();
        return Result.success("操作成功");
    }

}




